<?php

namespace p5\objects;

/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2015/11/24
 * Time: 8:48
 */
class PropertyUtils
{
    public static function setProperty(&$object, $name, $value)
    {
        if (is_array($object)) {
            $object[$name] = $value;
        } else if (gettype($object) === "object") {
            try {
                $object->$name = $value;
            } catch (\Exception $e) {
                BeanUtils::setProperty($object, $name, $value);
            }
        } else {
            BeanUtils::setProperty($object, $name, $value);
        }
    }

    public static function set(&$object, $name, $value)
    {
        self::setProperty($object, $name, $value);
    }

    /**
     * @param $object
     * @param $method
     * @param $value
     * @return mixed|string
     */
    public static function getProperty($object, $name, $defaultValue = "")
    {
        if (is_array($object)) {
            if (array_key_exists($name, $object)) {
                return $object[$name];
            }
            return $defaultValue;
        }
        return BeanUtils::getProperty($object, $name, $defaultValue);
    }

    public static function first($object, $names, $defaultValue = "")
    {
        $names = is_string($names) ? explode(",", $names) : $names;
        for ($i = 0; $i < count($names); $i++) {
            $value = static::get($object, $names[$i]);
            if (!empty($value)) {
                return $value;
            }
        }
        return $defaultValue;
    }

    public static function get($object, $name, $defaultValue = "")
    {
        return self::getProperty($object, $name, $defaultValue);
    }

    public static function getMagic($object, $name, $defaultValue = "")
    {
        $names = explode(".", $name);
        $temp = $object;
        $random = "--2239skJMDIKEsdw99sasd---";
        foreach ($names as $name) {
            $temp = static::get($temp, $name, $random);
            if ($temp === $random) {
                return $defaultValue;
            }
        }
        return $temp;
    }
}